import { useNavigate } from 'react-router-dom';
import React, { useState } from 'react';
import { Button, Checkbox, Form, type FormProps, Input, Spin } from 'antd';
import { login } from '@/api/login';

type FieldType = {
  username: string;
  password: string;
  remember?: string;
};

const Login: React.FC = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    // if (values.username === 'admin' && values.password === '123456') {
    // 	// console.log('Success:', values);
    // 	const token = window.btoa(encodeURIComponent(JSON.stringify({username: values.username, password: values.password})))
    // 	localStorage.setItem('token', token)
    // 	navigate('/')
    // }
    setLoading(true)
    login(values).then(res => {
      if (res.code === 200) {
        localStorage.setItem('token', res.data.access_token)
        navigate('/')
      }
    }).finally(() => {
      setLoading(false)
    })
  };
	
  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (errorInfo) => {
    // console.log('Failed:', errorInfo);
  };

  return (
    <div className='w-full h-lvh flex justify-center content-center items-center'>
      <Spin spinning={loading}>
        <Form
          name="basic"
          layout='vertical'
          // labelCol={{ span: 8 }}
          // wrapperCol={{ span: 16 }}
          className='w-[400px]'
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="Username"
            name="username"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="Password"
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>

          {/* <Form.Item<FieldType>
            name="remember"
            valuePropName="checked"
          >
            <Checkbox>Remember me</Checkbox>
          </Form.Item> */}

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
							登录
            </Button>
          </Form.Item>
        </Form>
      </Spin>
    </div>
  )
}

export default Login;